<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
// 加载搜索联想建议请求的方法
import { getSearchSuggestions } from '@/api/search'
// 加载搜索防抖功能的方法
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  data() {
    return {
      suggestions: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  // 监听函数(用于监听组件发生的变化)
  watch: {
    searchText: {
      // header():内置固定函数,监听的对象发生变化时调用.
      // immediate: 用于监听开始后,立即调用监听函数
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      immediate: true
    }
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('请求失败!')
      }
    },
    highlight(text) {
      // 定义正则模板
      const highlightStr = `<span class="active">${this.searchText}</span>`
      // 调用正则构造函数
      // 参数1:匹配的字符串  参数2:匹配规则(全局适用)
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active {
    color: red;
  }
}
</style>